import json
from django.core import serializers
from django.http import JsonResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters  # 注意
from rest_framework.pagination import PageNumberPagination

from UShop.models import TbGoods, Sku, TbGoodsCategory
from goods.filter import SkuFilter, SpuFilter
from .serializer import SkuSerializer, GoodsSerializer, GSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets, mixins


class SkuPagination(PageNumberPagination):
    # 分页
    page_size = 5
    page_size_query_param = 'page_size'
    page_query_param = "p"
    max_page_size = 1000

class SpuPagination(PageNumberPagination):
    # 分页
    page_size = 5
    page_size_query_param = 'page_size'
    page_query_param = "p"
    max_page_size = 1000

class SkuListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''
    商品SKU列表
    '''
    queryset = Sku.objects.get_queryset().order_by('sku_id')
    serializer_class = SkuSerializer

    pagination_class = SkuPagination

    filter_backends = (DjangoFilterBackend,filters.SearchFilter)
    filter_class = SkuFilter
    search_fields = ('sku_name',)


class SpuListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''
    商品SpU列表
    '''
    queryset = TbGoods.objects.get_queryset().order_by('spu_id')
    serializer_class = GSerializer

    pagination_class = SpuPagination

    filter_backends = (DjangoFilterBackend,filters.SearchFilter)
    filter_class = SpuFilter
    search_fields = ('sup_name',)


def GoodsDetail(request, *args, **kwargs):
    bid = kwargs['bid']
    sid = kwargs['sid']
    if bid == 00:
        goods_list = TbGoods.objects.all()
        if sid == 00:
            goods_list = goods_list
        else:
            goods_list = goods_list.filter(spu_brand=sid)
    else:
        category_list =TbGoods.objects.filter(spu_category=bid)
        if sid == 00:
            goods_list = category_list
        else:
            goods_list = category_list.filter(spu_brand=sid)

    data = serializers.serialize("json", goods_list)
    return JsonResponse(data,safe=False)


class phoneViewSet(viewsets.ReadOnlyModelViewSet):
    '''
    手机SPU列表
    '''
    queryset = TbGoods.objects.all()
    serializer_class = GoodsSerializer

    def get_queryset(self):  # 过滤函数
        return self.queryset.filter(spu_category_id=0)


class PcViewSet(viewsets.ReadOnlyModelViewSet):
    '''
    电脑SPU列表
    '''
    queryset = TbGoods.objects.all()
    serializer_class = GoodsSerializer

    def get_queryset(self):  # 过滤函数
        return self.queryset.filter(spu_category_id=1)

